import { Button, Card, message, Table } from "antd";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/router";
import './index.less';

/**
 * 组件：服务套餐购买页状态
 */
export interface ServerProjectBuyState extends ReactViewState {
  /** 购买者对象信息 */
  userinfo?: any;
  /** 购买商品信息 */
  productobj?: any;
  /** 订单列表 */
  order_list?: any[];
  /** 总金额 */
  total_amount?: number;
  // 行选择
  select_ids?: string[];
}

/**
 * 组件：服务套餐购买页
 */
export class ServerProjectBuy extends ReactView<ServerProjectBuyControl, ServerProjectBuyState> {
  constructor(props: any) {
    super(props);
    this.state = {
      userinfo: {},
      productobj: '',
      order_list: [],
      total_amount: 0,
      select_ids: [],
    };
  }
  componentDidMount() {
    // this.selectdata();
    /** 判断是否立即购买 */
    // if (this.props.match!.params.key) {
    //   let formValues = JSON.parse(this.props.match!.params.key);
    //   console.warn(formValues);
    //   let total_amount = 0;
    //   formValues.item_list.map((value: any, index: number) => {
    //     total_amount += value.item_price || 0;
    //   });
    //   total_amount = total_amount * formValues.count;
    //   AppServiceUtility.comfirm_order_service.get_purchaser_detail!()!
    //     .then((data) => {
    //       // console.info(data);
    //       this.setState({
    //         order_list: [formValues],
    //         total_amount,
    //         userinfo: data['personnel_info']
    //       });
    //     })
    //     .catch((err) => {
    //       console.info(err);
    //     });
    // } else {
    let storage = window.localStorage;
    let shop = storage.getItem('shop');
    let shop_list: any[] = [];
    let shop_obj_list: any[] = [];
    let total_amount = 0;
    if (shop) {
      shop_list = shop.split('___');
      shop_list.map(value => {
        shop_obj_list.push(JSON.parse(value));
      });
      shop_obj_list.map(order => {
        total_amount += order['total_price'] || 0;
      });
      console.info(shop, shop_obj_list);
      AppServiceUtility.comfirm_order_service.get_purchaser_detail!()!
        .then((data) => {
          // console.info(data);
          this.setState({
            order_list: shop_obj_list,
            total_amount,
            userinfo: data['personnel_info']
          });
        })
        .catch((err) => {
          console.info(err);
        });
    }
    // }

  }
  selectdata() {
    if (!this.props.match!.params.key) {
      return;
    }
    AppServiceUtility.service_item_serviceinfo.get_service_product_package_detail!({ id: JSON.parse(this.props.match!.params.key).service_product_id }, 1, 1)!
      .then((res) => {
        console.warn(JSON.parse(this.props.match!.params.key));
        this.setState({
          productobj: {
            service_product_id: JSON.parse(this.props.match!.params.key).service_product_id,
            item_list: JSON.parse(this.props.match!.params.key).item_list,
            name: res[0].name,
            // introduce: JSON.parse(this.props.match!.params.key).introduce,
            count: JSON.parse(this.props.match!.params.key).count,
            img: res[0].picture_collection ? res[0].picture_collection[0] : ''
          }
        });
      });
    // AppServiceUtility.comfirm_order_service.get_purchaser_detail!()!
    //   .then((res) => {
    //     this.setState({
    //       userinfo: res['personnel_info']
    //     });
    //   });
  }
  /** 计算总价格 */
  money(product: any) {
    let moneys: number = 0;
    product.item_list!.map((item: any) => {
      moneys += (product.count * item.item_price);
    });
    return moneys;
  }

  /** 下单 */
  // order() {
  //   console.log(this.state.productobj);
  //   AppServiceUtility.comfirm_order_service.create_product_order!(this.state.productobj)!
  //     .then((res) => {
  //       if (res === 'Success') {
  //         message.info('订单创建成功');
  //         this.props.history!.push(ROUTE_PATH.serviceOrder);
  //       }
  //     });
  // }

  order() {
    AppServiceUtility.comfirm_order_service.create_product_order!(this.state.order_list)!
      .then((data) => {
        console.info(data);
        if (data === 'Success') {
          message.info('订单创建成功');
          // window.localStorage.clear();
          this.props.history!.push(ROUTE_PATH.serviceOrder);
        }
      })
      .catch((err) => {
        console.info(err);
      });
  }
  // 全部删除
  deleteAll() {
    const select_ids = this.state.select_ids;
    select_ids!.map((item: any, index: number) => {
      this.deleteOrder(item);
    });
    this.setState({
      select_ids: [],
    });
  }
  /** 订单删除 */
  deleteOrder = (index: number) => {
    let { order_list, total_amount } = this.state;
    let order_str_list: any[] = [];
    console.info(order_list![index]);
    total_amount = 0;
    order_list!.splice(index, 1);
    order_list!.map(order => {
      total_amount += order['total_price'];
      order_str_list.push(JSON.stringify(order));
    });
    let shop = order_str_list.join('___');
    window.localStorage.setItem('shop', shop);
    this.setState({
      order_list,
      total_amount
    });
  }
  back() {
    this.props.history!.push(ROUTE_PATH.serviceProjectindex);
  }
  onSelectChange = (selectedRowKeys: any[], selectedRows: any) => {
    let ids: string[] = [];
    selectedRowKeys = selectedRowKeys!.map((item: any, idx: number) => {
      ids.push(item);
    });
    this.setState({
      select_ids: ids
    });
  }
  render() {
    const columns = [
      {
        title: '图片',
        dataIndex: 'img',
        render: (text: any, record: any) => (
          <span className="service-project-buy-pic">
            <img src={text} />
          </span>
        ),
      },
      {
        title: '名称',
        dataIndex: 'name',
      },
      {
        title: '项目',
        dataIndex: 'item',
      },
      {
        title: '服务地址',
        dataIndex: 'address',
      },
      {
        title: '服务人员',
        dataIndex: 'person',
      },
      {
        title: '联系方式',
        dataIndex: 'contact',
      },
      {
        title: '数量',
        dataIndex: 'count',
      },
      {
        title: '价格',
        dataIndex: 'prize',
      },
      {
        title: '操作',
        dataIndex: 'ctrl',
        render: (text: any, record: any) => (
          <Button type="danger" onClick={this.deleteOrder.bind(this, record.id)}>
            删除
          </Button>
        ),
      },
    ];
    let data = this.state.order_list!.map((productobj, index) => {
      let itm = productobj.item_list && productobj.item_list.length > 0 ? productobj.item_list!.map((item: any, index: number) => {
        return item.item_name;
      }) : '';
      return {
        service_product_id: productobj.service_product_id || '',
        img: productobj.img || '',
        name: productobj.name || '',
        item: itm || '',
        address: this.state.userinfo.address ? this.state.userinfo.address : '',
        person: this.state.userinfo.name ? this.state.userinfo.name : '',
        contact: this.state.userinfo.telephone ? this.state.userinfo.telephone : '',
        count: productobj.count || 0,
        prize: this.money(productobj) || 0,
      };
    });
    const rowSelection: any = {
      onChange: this.onSelectChange,
      hideDefaultSelections: true,
      type: 'checkbox',
      selectedRowKeys: this.state.select_ids ? this.state.select_ids : []
    };
    return (
      <Card className="service-project-buy-card">
        <Table rowSelection={rowSelection} columns={columns} dataSource={data} />
        <div className="service-project-buy-btm">
          <div className="left">
            <Button type="danger" onClick={() => { this.deleteAll(); }}>删除所选</Button>
          </div>
          <div className="right">
            <span className="service-project-buy-prize">总价格：{this.state.total_amount || 0}</span>
            <Button onClick={() => { this.back(); }}>返回列表</Button>
            <Button type="primary" onClick={() => { this.order(); }}>确认订单</Button>
          </div>
        </div>
      </Card>
    );
  }
}

/**
 * 组件：服务套餐购买页
 * 服务套餐购买页
 */
@addon('ServerProjectBuy', '服务套餐购买页', '描述')
@reactControl(ServerProjectBuy, true)
export class ServerProjectBuyControl extends ReactViewControl {
  constructor() {
    super();
  }
}
